//
//  TTRequest.m
//  WxIOSReaderForiPhone
//
//  Created by apan on 17/5/11.
//  Copyright © 2017年 anzeinfo. All rights reserved.
//

#import "TTRequest.h"
#import "GTMBase64.h"

@implementation TTRequest

- (instancetype)init
{
    self = [super init];
    if (self) {
        _manager = [AFHTTPSessionManager manager];
        [_manager.securityPolicy setAllowInvalidCertificates:NO];
        _manager.requestSerializer = [AFHTTPRequestSerializer serializer]; // 字典
        _manager.responseSerializer = [AFHTTPResponseSerializer serializer];//响应(手动解析)不设置会报-1016或者会有编码问题
        _manager.requestSerializer.stringEncoding = kCFStringEncodingUTF8;
        _manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json",@"text/javascript",@"text/html",@"text/xml",@"application/xml", nil];//不设置会报 error 3840
        _manager.requestSerializer.timeoutInterval = HTTP_TIME_OUT; //清求时间设置
    }
    return self;
}

//对nsstring进行Base64加密
-(NSString*) string2Base64String:(NSString*)_string{
    NSData *base64Data = [GTMBase64 encodeData:[_string dataUsingEncoding:NSUTF8StringEncoding]];
    NSString *base64RequestData = [[NSString alloc] initWithData:base64Data encoding:NSUTF8StringEncoding];
    return base64RequestData;
}

//对nsdata进行Base64加密
-(NSString*) data2Base64String:(NSData*)_data{
    NSData *base64Data = [GTMBase64 encodeData:_data];
    NSString *base64RequestData = [[NSString alloc] initWithData:base64Data encoding:NSUTF8StringEncoding];
    return base64RequestData;
}

/**
 组装Get方式的URL

 @param url url description
 @param param param description
 @return return value description
 */
-(NSString*)getUrlByParam:(NSString*)url
                withParam:(NSDictionary* _Nullable)param{
    NSString *retUrl = [NSString stringWithFormat:@"%@?",url];
    for(NSString *key in param){
        retUrl = [NSString stringWithFormat:@"&%@=%@",key,[param objectForKey:key]];
    }
    return retUrl;
}

/**
 二次包装的方法，根据参数选择post或get方法
 */
-(void)RequestServer:(AFHTTPSessionManager *)manager
                 url:(NSString *)URLString
          parameters:(id _Nullable)parameters
            progress:(void (^ _Nullable)(NSProgress *))downloadProgress
             success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success
             failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure{
    if(parameters == nil){
        [manager GET:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if(success){
                success(task,responseObject);
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if(failure){
                failure(task,error);
            }
        }];
    }else{
        [manager POST:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if(success){
                success(task,responseObject);
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if(failure){
                failure(task,error);
            }
        }];
    }
}

/*
 发起异步网络请求
 */
-(void)asynRequestServerAndParser:(NSString*)url
                     withPostData:(NSDictionary* _Nullable)postData
                  withParserModal:(TTInterfaceModel*)modal
                      withSuccess:(void(^)(TTInterfaceModel* model))onSuccess
                         withFail:(void(^)(NSString* error))onFail{
    //这里重新封装了RequestServer方法，根据postData值选择GET或Post方法
    __weak typeof(self)weakSelf = self;
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    [weakSelf RequestServer:weakSelf.manager url:url parameters:postData progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
        NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"%@",result);
        @try{
            TTInterfaceModel *retModal = nil;
            if(modal){
                retModal = [modal Paser:result];
            }
            //通过回调通知ui层
            if(onSuccess){
                onSuccess(retModal);
            }
        }@catch (NSException *exception) {
            NSLog(@"无法解析回送数据，回送信息格式有误， %@", exception);
            if(onFail){
                onFail([NSString stringWithFormat:@"解析返回数据失败,原因:%@",exception]);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
        NSString *errorInfo = @"";
        if (error) {
            switch (error.code) {
                case -1001:
                    errorInfo = @"连接服务器超时.";
                    break;
                case -1003:
                    errorInfo = @"无法链接到指定的网络地址.";
                    break;
                case -1004:
                    errorInfo = @"无法连接到服务器.";
                    break;
                case -1011:
                    errorInfo = [NSString stringWithFormat:@"服务器错误，请稍后重试，如问题依旧，请联系管理员.［%ld］",(long)error.code];
                    break;
                case -1022:
                    errorInfo = [NSString stringWithFormat:@"服务器不支持https请求，错误代码:［%ld］",(long)error.code];
                    break;
                case -1200:
                    errorInfo = [NSString stringWithFormat:@"发生了SSL错误，无法建立与该服务器的安全连接，错误代码:［%ld］",(long)error.code];
                    break;
                default:
                    errorInfo = [NSString stringWithFormat:@"发生未知错误，请返回重试.［%ld］", (long)error.code];
                    break;
            }
        }
        NSLog(@"请求发生错误：%@", error);
        //通过回调通知ui层
        if(onFail){
            onFail([NSString stringWithFormat:@"服务器连接失败,原因:%@",errorInfo]);
        }
    }];
    
}

@end
